package com.zcf.dao.Impl;

import com.zcf.dao.UserDao;
import com.zcf.domain.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by 11481 on 2017/2/27.
 */
@Repository
public class UserDaoImpl implements UserDao{
    @Resource
    private SessionFactory sessionFactory;
    protected Session getSession(){
        Session session = sessionFactory.getCurrentSession();
        return session;
    }
    @Override
    public boolean findByName(String username) {
        Transaction transaction = getSession().beginTransaction();
        User user = null;
        user = (User)getSession().createQuery("from User u where u.username=?")
                .setParameter(0,username)
                .uniqueResult();
        if(user!=null){
            transaction.commit();
            getSession().close();
            return true;
        }
        transaction.commit();
        getSession().close();
        return false;
    }

    @Override
    public void register(String username, String password) {

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        getSession().save(user);
    }

    @Override
    public boolean findByUser(String username, String password) {
        User user = null;
        user = (User)getSession().createQuery("from User u where u.username=? and u.password=?")
                .setParameter(0,username)
                .setParameter(1,password)
                .uniqueResult();
        if (user!=null){
            return true;
        }
        return false;
    }

    @Override
    public List<User> findByAll() {
      return  getSession().createQuery("from User").list();

    }
}
